// 获取电影评分统计数据
function getRatingStats() {
    console.log('Fetching all movies...');
    fetch('http://127.0.0.1:5000/')
        .then(response => response.json())
        .then(data => {
            console.log('Received data:', data);
            // 计算所有电影数量
            const total = data.length;
            updateRatingCount({ total });
        })
        .catch(error => console.error('Error:', error));
}

// 更新评分统计显示
function updateRatingCount(data) {
    const totalMoviesElement = document.getElementById('total-movies-rating');
    if (totalMoviesElement) {
        totalMoviesElement.textContent = data.total || 0;
        console.log('Updated count:', data.total);
    }
}

// 为筛选按钮添加点击事件
document.addEventListener('DOMContentLoaded', function() {
    console.log('DOM loaded, setting up click handlers...');
    const filterLinks = document.querySelectorAll('.filter a');
    console.log('Found filter links:', filterLinks.length);
    
    filterLinks.forEach(link => {
        link.addEventListener('click', function(e) {
            e.preventDefault(); // 阻止默认行为
            console.log('Link clicked:', this.textContent);
            
            // 移除所有active类
            filterLinks.forEach(l => l.classList.remove('active'));
            // 添加active类到当前点击的链接
            this.classList.add('active');
            
            // 获取评分范围
            const ratingRange = this.textContent;
            console.log('Selected range:', ratingRange);
            
            if (ratingRange === '全部') {
                getRatingStats();
            } else {
                // 解析评分范围
                const range = ratingRange.replace('分', '').split('-');
                if (range.length === 2) {
                    const minRating = parseFloat(range[0]);
                    const maxRating = parseFloat(range[1]);
                    console.log('Filtering by rating range:', minRating, 'to', maxRating);
                    
                    fetch('http://127.0.0.1:5000/')
                        .then(response => response.json())
                        .then(data => {
                            // 根据评分范围过滤电影
                            const filteredMovies = data.filter(movie => 
                                movie.rating >= minRating && movie.rating < maxRating
                            );
                            console.log('Filtered movies count:', filteredMovies.length);
                            updateRatingCount({ total: filteredMovies.length });
                        })
                        .catch(error => console.error('Error:', error));
                }
            }
        });
    });

    // 初始加载全部数据
    getRatingStats();
}); 